package com.pn.controller;


import com.google.code.kaptcha.Producer;
import com.pn.entity.*;
import com.pn.service.AuthService;
import com.pn.service.UserService;
import com.pn.utils.DigestUtil;
import com.pn.utils.TokenUtils;
import com.pn.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
public class LoginController {

    @Resource(name = "captchaProducer")
    private Producer producer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/captcha/captchaImage")
    public void captchaImage(HttpServletResponse response){

        ServletOutputStream out = null;


        try {
            String text = producer.createText();

            BufferedImage image = producer.createImage(text);

            redisTemplate.opsForValue().set(text, "", 60*30, TimeUnit.SECONDS);

            response.setContentType("image/jpeg");
            out = response.getOutputStream();

            ImageIO.write(image, "jpg", out);
            out.flush();

        }catch (IOException e){
             e.printStackTrace();
        }finally {
            try {
                if(out != null){
                    out.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }

        }




    }

    @Autowired
    private UserService userService;

    @Autowired
    private TokenUtils tokenUtils;

    /**
     * 登录
     * @param loginUser
     * @return
     */
    @RequestMapping("/login")
    public Result login(@RequestBody LoginUser loginUser){
        String code = loginUser.getVerificationCode();
        if(!redisTemplate.hasKey(code)){
            return Result.err(Result.CODE_ERR_BUSINESS, "验证码错误");
        }


        User user = userService.queryUserByCode(loginUser.getUserCode());
        if(user != null) {
            if (user.getUserState().equals(WarehouseConstants.USER_STATE_PASS)) {
                //用户审核
                String userPwd = loginUser.getUserPwd();
                userPwd = DigestUtil.hmacSign(userPwd);
                if(userPwd.equals(user.getUserPwd())){
                    CurrentUser currentUser = new CurrentUser(user.getUserId(), user.getUserCode(), user.getUserName());

                    String token = tokenUtils.loginSign(currentUser, userPwd);
                    return  Result.ok("登录成功", token);
                }else {
                    //密码错误
                    return Result.err(Result.CODE_ERR_BUSINESS, "密码错误");
                }
            }else{
                //用户未审核
                return Result.err(Result.CODE_ERR_BUSINESS, "用户未审核");
            }
        }else{
            return Result.err(Result.CODE_ERR_BUSINESS, "账号不存在");
        }

    }

    @RequestMapping("curr-user")
    public Result currentUser(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        return Result.ok(currentUser);
    }

    @Autowired
    private AuthService authService;
    /**
     * 加载当前登录用户权限(菜单)树的url接口/user/auth-list
     *
     * @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String clientToken
     * 将请求头Token的值即前端归还的token,赋值给请求处理方法的参数String clientToken
     */
    @GetMapping("/user/auth-list")
    public Result authList(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME)
                           String clientToken) {
        //从前端归还的token中解析出当前登录用户的信息
        CurrentUser currentUser = tokenUtils.getCurrentUser(clientToken);
        //根据用户id查询用户权限(菜单)树
        List<Auth> authTreeList = authService.authTreeByUid(currentUser.getUserId());
        //响应
        return Result.ok(authTreeList);
    }

    /**
     *
     * @param token
     * @return
     */
    @RequestMapping("/logout")
    public Result logout(@RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        redisTemplate.delete(token);

        return Result.ok("退出系统！");
    }
}
